import { login, logout, getInfo, visitorLogin } from '@/api/user'
import { newlogin, newgetInfo, loginInfo } from '@/api/newuser'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter, constantRoutes } from '@/router'
import { MessageBox, Message } from 'element-ui'
import { userRouter } from "@/utils/userRouter"
import { newuserRouter } from "@/utils/newuserRouter"
import { userRouterNewConfig } from "@/utils/userRouterNewConfig"
import { userRouterNewChildrenConfigOne } from "@/utils/userRouterNewChildrenConfigOne"
import { userRouterNewChildrenConfigTwo } from "@/utils/userRouterNewChildrenConfigTwo"
import { newuserRouterChildren } from "@/utils/newuserRouterChildren"
import { adminRouter } from "@/utils/adminRouter"


const state = {
  token: getToken(),
  name: '',
  avatar: '',
  type: '',
  region_id: '',
  is_admin: '',
  is_admin_view: '',
  introduction: '',
  newtype: null,
  rid: '',
  roles: [],
  seach: '',
  menuList: [],
  allRouter: constantRoutes,
  department_id: '',
  over_day: '',
  url:'',
  role: [],
  telephone: '',
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NEWTYPE: (state, newtype) => {
    state.newtype = newtype
  },
  SET_NEWTOKEN: (state, token) => {
    state.newtoken = token
  },

  SET_IS_ADMIN: (state, is_admin) => {
    state.is_admin = is_admin
  },
  SET_REGIONID: (state, region_id) => {
    state.region_id = region_id
  },
  SET_TYPE: (state, type) => {
    state.type = type
  },
  SET_ADMIN: (state, is_admin_view) => {
    state.is_admin_view = is_admin_view
  },
  SET_RID: (state, rid) => {
    state.rid = rid
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_COMID: (state, com_id) => {
    state.com_id = com_id
  },
  SET_ADMINNAME: (state, admin_name) => {
    state.admin_name = admin_name
  },
  SET_PID: (state, pid) => {
    state.pid = pid
  },
  SET_STREETID: (state, street_id) => {
    state.street_id = street_id
  },
  SET_STREETNAME: (state, street_name) => {
    state.street_name = street_name
  },
  SET_DEPARTMENTID: (state, department_id) => {
    state.department_id = department_id
  },
  SET_OVERDAT: (state, over_day) => {
    state.over_day = over_day
  },
  SET_URL: (state, url) => {
    state.url = url
  },
  SET_ROLE: (state, role) => {
    state.role = role
  },
  SET_TELEPHONE: (state, telephone) => {
    state.telephone = telephone
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROUTER: (state, route) => {
    // console.log(route,'ROUTER')
    state.menuList = route;
    // state.allRouter = constantRoutes.concat(route)
    // console.log(state.menuList)
    // console.log(state.allRouter)
  },
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { mobile, password, checked ,type } = userInfo;
    return new Promise((resolve, reject) => {
      login({ login: mobile.trim(), password: password , type: type }).then(response => {

        if (checked) {
          localStorage.setItem("mobile", mobile)
          localStorage.setItem("password", password)
        } else {
          localStorage.setItem("mobile", '')
          localStorage.setItem("password", '')
        }
        // loginInfo({ account: mobile.trim(), password: password }).then(response => {
        //   sessionStorage.setItem("tokenIfon", response.token)
        // })

        commit('SET_TOKEN', response.token)
        // console.log('type设置',type);
        if(type){
          commit('SET_NEWTYPE', type)
          sessionStorage.setItem("newtype", type)
        }else {
          commit('SET_NEWTYPE', 1)
          sessionStorage.setItem("newtype", 1)
        }
        
        setToken(response.token)
        localStorage.setItem("token", response.token)
        sessionStorage.setItem("token", response.token)
        resolve()
      }).catch(error => {
        reject(error)
        Message.error({
          message: error,
          type: 'error',
        })
      })
    })
  },

  

  visitor({ commit }, userInfo) {
    const { mobile, code } = userInfo;
    // console.log(userInfo,'userInfo');
    return new Promise((resolve, reject) => {
      visitorLogin({ mobile: mobile.trim(), code: code }).then(response => {
        commit('SET_TOKEN', response.token)
        
        setToken(response.token)
        sessionStorage.setItem("token", response.token)
        localStorage.setItem("token", response.token)
        resolve()
      }).catch(error => {
        reject(error)
        Message.error({
          message: error,
          type: 'error',
        })
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({ token: state.token,type: Number(sessionStorage.getItem("newtype"))}).then(response => {
        if (!response) {
          reject('验证失败，请重新登录。')
        }
        const { over_day, is_admin, username,admin_name, region_id, thumb, introduction, is_admin_view, rid, id, com_id,pid,street_id,street_name, department_id } = response.info
        const {type} = response.auth


        localStorage.setItem("avatar", thumb)
        // console.log(is_admin_view,1234)
        sessionStorage.getItem("user", is_admin)
        const roles = is_admin
        commit('SET_ROLES', roles)
        commit('SET_IS_ADMIN', is_admin)
        commit('SET_TYPE', type)
        commit('SET_REGIONID', region_id)
        commit('SET_NAME', username)
        commit('SET_AVATAR', thumb)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_ADMIN', is_admin_view)
        commit('SET_RID', rid)
        commit('SET_ID', id)
        commit('SET_COMID', com_id)
        commit('SET_ADMINNAME', admin_name)
        commit('SET_PID', pid)
        commit('SET_STREETID', street_id)
        commit('SET_STREETNAME', street_name)
        commit('SET_DEPARTMENTID', department_id)
        commit('SET_OVERDAT', over_day)
        commit('SET_URL', response.url)
        commit('SET_ROLE', response.role)

        if(response.region){
          commit('SET_TELEPHONE', response.region.telephone)
        }
        
        // roles must be a non-empty array
        // if (roles == '') {
        //   // roles 改 is_admin
        //   reject('getInfo: roles must be a non-null array!')
        // }

        resolve(response)

      }).catch(error => {
        reject(error)
        Message.error({
          message: error,
          type: 'error',
        })
      })
    })
  },


  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
        Message.error({
          message: error,
          type: 'error',
        })
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_NEWTOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    // console.log(dispatch,'dispatch')
    // console.log(commit,'commit')
    return new Promise(async resolve => {
      const dataInfo = await dispatch('getInfo')
      let accessRoutes
      if(dataInfo.auth.type == 1){
         accessRoutes = userRouterNewConfig;
      }else if(dataInfo.auth.type == 2){
         accessRoutes = userRouterNewChildrenConfigOne;
      } else {
        accessRoutes = userRouterNewChildrenConfigTwo;
      }
      commit("SET_ROUTER", accessRoutes)
      router.addRoutes(accessRoutes)
      router.options.routes = accessRoutes
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
